#include <thread>

#include "TaskExportapp.h"
#include "ServiceConnection.h"
#include "App.h"
#include "AdbHelper.h"


namespace Gnodroid {
    TaskExportapp::TaskExportapp(std::string pid,
                                 std::string destPath) :
        Task(TaskProgressType::NONE)
    {
        m_pid = pid;
        m_destPath = destPath;
    }

    void
    TaskExportapp::start()
    {
        updateState(TaskState::RUNNING);
        updateLabel(std::string("export app ") + m_pid);
        updateMessage("Exporting");

        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(App::getService(SERVICE_CONNECTION));

        if (!serviceConnection->isConnecting()) {
            updateMessage("Not connected");
            updateState(TaskState::ERROR);
            return;
        }

        std::thread t(sigc::mem_fun(*this, &TaskExportapp::__exportAppThread));
        t.detach();
        return;
    }

    void
    TaskExportapp::__exportAppThread()
    {
        ServiceConnection* serviceConnection = static_cast<ServiceConnection*>(App::getService(SERVICE_CONNECTION));

        if (!AdbHelper::exportApp(serviceConnection->getAdbPath(),
                                  serviceConnection->getDeviceId(),
                                  m_pid,
                                  m_destPath)) {
            updateMessage("export app failed");
            updateState(TaskState::ERROR);
            return;
        }

        updateMessage("Success");
        updateState(TaskState::FINNISHED);
        return;
    }
}
